//
//  EFAModel.m
//  efairy
//
//  Created by XiangDongMBP on 2017/7/26.
//  Copyright © 2017年 East. All rights reserved.
//

#import "EFAModel.h"
#import "GlobalHeader.h"
#import <RongIMLib/RongIMLib.h>
#import <JPUSHService.h>
#import "GTSDK/GeTuiSdk.h"


static NSString *const kEFAModelFilePath = @"kEFAModelFilePath";

@implementation EFAModel
// NSKeyedArchiver、NSKeyedUnarchiver
- (void)encodeWithCoder:(NSCoder *)aCoder { [self yy_modelEncodeWithCoder:aCoder]; }
- (instancetype)initWithCoder:(NSCoder *)aDecoder { self = [super init]; return [self yy_modelInitWithCoder:aDecoder]; }

+ (instancetype)sharedInstance {
    static EFAModel *sharedInstance = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        sharedInstance = [[self alloc] init];
    });
    return sharedInstance;
}
- (BOOL)saveToDisk {
    return [NSKeyedArchiver archiveRootObject:self toFile:[self getModelFilePath]];
}
- (BOOL)getFromDisk {
    EFAModel *temp = [NSKeyedUnarchiver unarchiveObjectWithFile:[self getModelFilePath]];
    if (!temp) {
        return NO;
    }
    
    self.loginInfo = temp.loginInfo;
    self.projectModel = temp.projectModel;
    self.deviceModel = temp.deviceModel;
    return YES;
}
- (NSString *)getModelFilePath {
    NSString *document = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject];
    return [document stringByAppendingPathComponent:kEFAModelFilePath];
}

@end



#pragma mark - 登录相关
@implementation EFAModel (LoginRelative)
- (BOOL)isNewVersion {
    NSString *appVersion = [[NSUserDefaults standardUserDefaults] objectForKey:EFAGlobalUserDefaultsAppVersion];
    NSString *curVersion = [[[NSBundle mainBundle] infoDictionary] objectForKey:@"CFBundleShortVersionString"];
    if ([curVersion isEqualToString:appVersion]) {
        return NO;
    }
    
    [[NSUserDefaults standardUserDefaults] setObject:curVersion forKey:EFAGlobalUserDefaultsAppVersion];
    return YES;
}
- (BOOL)isLogin {
    return self.loginInfo ? YES: NO;
}
- (EFALoginModel *)loginModelWithDictionary:(NSDictionary *)dic {
    if ([dic[EFAGlobalJsonKeyErrCode] integerValue] == 200) {
        self.loginInfo = [EFALoginModel yy_modelWithDictionary:dic[EFAGlobalJsonKeyResult]];
        //绑定个推别名
        [self bindGeTuiAlias];
        // 极光推送绑定别名
        [self bindJPUSHAlias];
        // 登录成功连接融云
//        [self rongCloudOnLine];
        // 保存用户数据
        [self saveToDisk];
        // 保存用户帐号
        [[NSUserDefaults standardUserDefaults] setObject:self.loginInfo.user_info.efairyuser_phonenumber forKey:EFAGlobalUserDefaultsAccount];
    }
    return self.loginInfo;
}
- (void)refreshUserInfoWithDictionary:(NSDictionary *)dic {
    if ([dic[EFAGlobalJsonKeyErrCode] integerValue] == 200) {
        EFALoginUserInfo *temp = [EFALoginUserInfo yy_modelWithDictionary:dic[EFAGlobalJsonKeyResult]];
        self.loginInfo.user_info.efairyrole_level = temp.efairyrole_level;
        self.loginInfo.user_info.efairyuser_headimg_url = temp.efairyuser_headimg_url;
        self.loginInfo.user_info.efairyuser_nickname = temp.efairyuser_nickname;
    }
}
- (void)rongCloudOnLine {
    if (!self.loginInfo.rongcloud_token.length) {
        return;
    }
    // 断开融云的连接
    [[RCIMClient sharedRCIMClient] logout];
    // 融云开始连接
    [[RCIMClient sharedRCIMClient] connectWithToken:self.loginInfo.rongcloud_token success:^(NSString *userId) {
        NSLog(@"融云登陆成功。当前登录的用户ID：%@", userId);
    } error:^(RCConnectErrorCode status) {
        NSLog(@"融云登陆的错误码为:%ld", (long)status);
    } tokenIncorrect:^{
        //token过期或者不正确。
        //如果设置了token有效期并且token过期，请重新请求您的服务器获取新的token
        //如果没有设置token有效期却提示token错误，请检查您客户端和服务器的appkey是否匹配，还有检查您获取token的流程。
        NSLog(@"融云token错误");
    }];
}
- (void)bindJPUSHAlias {
    // 绑定极光推送Alias
    NSString *aliasStr = [NSString stringWithFormat:@"user_%zd", self.loginInfo.user_info.efairyuser_id];
    NSLog(@"极光推送的别名是%@", aliasStr);
    [JPUSHService setAlias:aliasStr completion:^(NSInteger iResCode, NSString *iAlias, NSInteger seq) {
        NSLog(@"极光设置别名完成：%ld, %@", (long)iResCode, iAlias);
    } seq:1];
}


-(void)bindGeTuiAlias{
    //绑定个推别名和序列号
    NSString *aliasStr = [NSString stringWithFormat:@"%zd", self.loginInfo.user_info.efairyuser_msgobj_id];
    NSString *sequenceNum = [NSString stringWithFormat:@"%zd", self.loginInfo.user_info.efairyuser_id];
    [GeTuiSdk bindAlias:aliasStr andSequenceNum:sequenceNum];
    
}

- (void)CheckJPUSHAlias {
    // 极光推送
    [JPUSHService getAlias:^(NSInteger iResCode, NSString *iAlias, NSInteger seq) {
        if (seq != 4) {
            return;
        }
        NSLog(@"获取别名返回：%ld, %@", (long)iResCode, iAlias);
        NSString *aliasStr = [NSString stringWithFormat:@"user_%ld", (long)self.loginInfo.user_info.efairyuser_id];
        if (!iAlias || ![iAlias isEqualToString:aliasStr]) {
            [self bindJPUSHAlias];
        }
    } seq:4];
}
- (void)logout {
    // 极光推送取消别名绑定
    [JPUSHService deleteAlias:^(NSInteger iResCode, NSString *iAlias, NSInteger seq) {
        NSLog(@"极光删除别名完成：%ld, %@", (long)iResCode, iAlias);
    } seq:2];
    // 融云断开连接
    [[RCIMClient sharedRCIMClient] logout];
    // 清理自动登录的标记(感觉这里的标记不用清)
//    [[NSUserDefaults standardUserDefaults] ];
    // 清空内存的个人数据
    self.loginInfo = nil;
    // 清空磁盘的个人数据
    [self saveToDisk];
}
@end


#pragma mark - 设备模块

@implementation EFAModel (DeviceRelative)
- (EFADeviceModel *)deviceModelWithDictionary:(NSDictionary *)dic {
    if ([dic[EFAGlobalJsonKeyErrCode] integerValue] == 200) {
        self.deviceModel = [EFADeviceModel yy_modelWithDictionary:dic[EFAGlobalJsonKeyResult]];
    }
    return self.deviceModel;
}
@end

#pragma mark - 应用模块
@implementation EFAModel (AppRelative)
- (EFAProjectModel *)projectModelWithDictionary:(NSDictionary *)dic {
    if ([dic[EFAGlobalJsonKeyErrCode] integerValue] == 200) {
        self.projectModel = [EFAProjectModel yy_modelWithDictionary:dic[EFAGlobalJsonKeyResult]];
    }
    return self.projectModel;
}

@end


